/**
 * Created by admin on 2018/8/1.
 */


const streamBuffers = require('stream-buffers');
const fs = require('fs');
const logUtil = require('../utils/log_util');
const { gridFs } = require('../utils/mongod_util');

/**
 * 判断文件是否存在
 * @param fileName
 * @param bucketName
 */
exports.exists = (fileName, bucketName) => new Promise((res, rej) => {
  gridFs().then((result) => {
    result.exists({
      filename: fileName,
      root: bucketName
    }, (err, found) => {
      if (err) rej(err);
      res(found);
    });
  }).catch((err) => {
    rej(err);
  });
});

/**
 * 删除文件
 * @type {Promise}
 */
exports.remove = (fileName, bucketName) => new Promise((res, rej) => {
  gridFs().then((result) => {
    result.remove({
      filename: fileName,
      root: bucketName
    }, (err) => {
      if (err) rej(err);
      res(true);
    });
  }).catch((err) => { rej(err); });
});

/**
 * 保存64位字符串
 * @param strImage
 * @param fileName
 * @param bucketName
 */
const saveImageByString = (strImage, fileName, bucketName) => new Promise((res, rej) => {
  if (!strImage) {
    logUtil.error('保存数据体不能为空');
    res('保存数据体不能为空');
  } else {
    gridFs().then((result) => {
      const writeStream = result.createWriteStream({
        filename: fileName,
        root: bucketName
      });
      const dataBuffer = new Buffer(strImage, 'base64');
      const readStreamBuffer = new streamBuffers.ReadableStreamBuffer();
      readStreamBuffer.put(dataBuffer);
      readStreamBuffer.pipe(writeStream);
      writeStream.on('close', () => {
        logUtil.info(`${fileName} Written To DB`);
        // readStreamBuffer.stop();
        res(true);
      });
      writeStream.on('error', (err) => {
        logUtil.error(err);
        //
        rej(err);
      });
      readStreamBuffer.stop();
    }).catch((err) => {
      logUtil.error(err);
      rej(err);
    });
  }
});


/**
 * 保存文件到Mongodb数据库
 * @param filePath
 * @param fileName
 * @param bucketName
 */
const saveFile = (filePath, fileName, bucketName) => new Promise((res, rej) => {
    // 写文件
  if (!filePath){
    logUtil.error("文件路径为空");
    res('文件路径为空');}
  else {
    gridFs().then((result) => {
      const writestream = result.createWriteStream({
        filename: fileName,
        root: bucketName
      });
      fs.createReadStream(filePath).pipe(writestream);

      writestream.on('close', (file) => {
        logUtil.info(`${file.filename} Written To DB`);
        res(true);
      });

      writestream.on('error', (err) => {
        logUtil.error(err);
        rej(err);
      });
    }).catch((err) => {
      logUtil.error(err);
      rej(err);
    });
  }
});


/**
 * 将文件或者64位字符串保存到数据库中
 * @param strImageOrfilePath
 * @param fileName
 * @param bucketName
 * @param isFile
 */
exports.save = (strImageOrfilePath, fileName, bucketName, isFile) => new Promise((res, rej) => {
  if (isFile) {
    saveFile(strImageOrfilePath, fileName, bucketName).then((result) => {
      res(true);
    }).catch((err) => {
      logUtil.error(err);
      rej(err);
    });
  } else {
    saveImageByString(strImageOrfilePath, fileName, bucketName).then((result) => {
      res(true);
    }).catch((err) => {
      logUtil.error(err);
      rej(err);
    });
  }
});


/**
 * 根据文件名称更新mongodb数据
 * @param strImageOrfilePath
 * @param fileName
 * @param bucketName
 * @param isFile
 */
exports.updateFile = (strImageOrfilePath, fileName, bucketName, isFile) => new Promise((res, rej) => {
  this.exists(fileName, bucketName).then((found) => {
    if (found) {
      this.remove(fileName, bucketName).then((result) => {
        this.save(strImageOrfilePath, fileName, bucketName, isFile).then(() => {
          res(true);
        }).catch((err) => {
          logUtil.error(err);
          rej(err);
        });
      }).catch((err) => {
        logUtil.error(err);
        rej(err);
      });
    } else {
      this.save(strImageOrfilePath, fileName, bucketName, isFile).then(() => {
        res(true);
      }).catch((err) => {
        logUtil.error(err);
        rej(err);
      });
    }
  }).catch((err) => {
    logUtil.error(err);
    rej(err);
  });
});

